package com.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.shop.bean.Goods;
import com.shop.dao.BaseDao;
import com.shop.dao.GoodsDao;

public class GoodsDaoImpl implements GoodsDao {

	@Override
	public List<Goods> selectAllGoods(int pageNum, int pageSize) {
		List<Goods> listGoods = new ArrayList<Goods>();
		Connection con = null;
		PreparedStatement pre = null;
		ResultSet res = null;
		String sql = "SELECT * FROM goods LIMIT ?,?";	
		try {
			con = BaseDao.getCon();
			pre = con.prepareStatement(sql);
			pre.setInt(1,(pageNum-1)*pageSize);
			pre.setInt(2,pageSize);
			res = pre.executeQuery();
			while(res.next()) {
				Goods goods = new Goods();
				goods.setGoodsId(res.getInt("goodsId"));
				goods.setGoodsName(res.getString("goodsName"));
				goods.setGoodsFactory(res.getString("goodsFactory"));
				goods.setGoodsType(res.getString("goodsType"));
				goods.setGoodsPrice(res.getDouble("goodsPrice"));
				goods.setGoodsNum(res.getInt("goodsNum"));
				listGoods.add(goods);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(res, pre, con);
		}
		return listGoods;
	}

	@Override
	public int selectGoodsRows() {
		// TODO Auto-generated method stub
		int rows = 0;
		Connection con = null;
		PreparedStatement pre = null;
		ResultSet res = null;
		String sql = "SELECT count(1) AS r FROM goods";	
		try {
			con = BaseDao.getCon();
			pre = con.prepareStatement(sql);
			res = pre.executeQuery();
			if(res.next()) {
				rows = res.getInt("r");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(res, pre, con);
		}
		return rows;
	}

	@Override
	public int deleteGoodsById(int goodsId) {
		int result = 0;
		Connection con = null;
		PreparedStatement pre = null;
		String sql = "DELETE FROM goods WHERE goodsId = ?";	
		try {
			con = BaseDao.getCon();
			pre = con.prepareStatement(sql);
			pre.setInt(1, goodsId);
			result = pre.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(null, pre, con);
		}
		return result;
	}

}
